package com.jingxing.controller;


import com.jingxing.config.ApiCode;
import com.jingxing.config.ApiResult;
import com.jingxing.pojo.UserInfo;
import com.jingxing.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录相关
 */
@Slf4j
@RestController
@Api(value = "API", tags = {"登录相关"})
public class LoginController {
    @Autowired
    private LoginService loginService;

    /**
     * 登录
     * @param phone
     * @param code
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "登录", notes = "登录", response = String.class)
    public ApiResult login(String phone, String code){
        if(phone== null){
            return ApiResult.parameterError("请输入手机号");
        }
        if (code== null) {
            return ApiResult.parameterError("请输入验证码");
        }
        String token = loginService.login(phone, code);
        if(token.equals("验证码过期")||token.equals("验证码错误")||token.equals("未报名")){
            return ApiResult.fail(token);
        }
        return ApiResult.ok(token);
    }

    /**
     * 根据token获取登录用户信息
     *
     * @return
     */
    @PostMapping("/getLoginInfo")
    @ApiOperation(value = "根据token获取登录用户信息", response = UserInfo.class)
    public ApiResult getLoginInfo(String token){
        if(token==null){
            return ApiResult.parameterError("token不能为空");
        }
        UserInfo userInfo = loginService.getLoginInfo(token);
        if(userInfo==null){
            return ApiResult.parameterError("token获取失败");
        }
        return ApiResult.result(ApiCode.SUCCESS,userInfo);

    }

    /**
     * 退出登录
     * @param request
     * @return String
     */
    @PostMapping("/logout")
    @ApiOperation(value = "退出登录", notes = "退出登录", response = String.class)
    public ApiResult<String> logout(HttpServletRequest request) {
        loginService.logout(request);
        return ApiResult.ok("退出成功");
    }

}
